home *** CD-ROM | disk | FTP | other *** search
- Path: news.rchland.ibm.com!usenet
- From: Philip Staite <pstaite+@rchland.ibm.com>
- Newsgroups: comp.lang.c++
- Subject: Re: inheritance of friendship
- Date: Fri, 05 Apr 1996 16:18:26 -0600
- Organization: IBM Rochester, MN
- Message-ID: <31659C32.41C6@rchland.ibm.com>
- References: <4k3ge2$igu@panoramix.fi.upm.es>
- NNTP-Posting-Host: powertool.rchland.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (X11; I; AIX 1)
-
- Sacha wrote:
- >
- > I've just read in the FAQ that friendship isn't inherited: that is if B is a
- > friend of class A, and class C is derived from B, C ISN'T a friend of A.
- >
- > A friends with B
- > |
- > not friends with C
- >
- > Is there some way around this?
- >
- > I am overloading << to output to streams, but I don't want to have to rewrite the
- > same function for each different type of stream. I've tried making both B and C
- > friends of A and defining the function for B, but this doesn't work.
- >
- > Should I just forget about overloading << and write an outToStream function
- > instead?
-
- I'm not sure exactly what you're trying to do, but here are a couple of
- examples of what you _can_ do...
-
-
- class foo {
- public:
- friend ostream& operator<<( ostream&, const foo& );
- };
-
- Now, this friend function provides stream io to *any* kind of ostream
- for class foo. That is, you can stream out to the console cout, a file
- via an ofstream, an in-memory buffer via an ostrstream, etc.
-
-
- OTOH, maybe you want to do something like:
-
- class foo {
- public:
- virtual ~foo() {} // always if deriving!!!
- inline friend ostream& operator<<( ostream&, const foo& );
- protected:
- virtual ostream& virtOut( ostream& ) const;
- };
-
- ostream& operator<<( ostream& o, const foo& f ) {
- return f.virtOut( o ); }
-
- ostream& foo::virtOut( ostream& o ) const {
- return o << "I'm a foo!"; }
-
- class bar : public foo {
- protected:
- virtual ostream& virtOut( ostream& ) const;
- };
-
- ostream& bar::virtOut( ostream& o ) const {
- return o << "I'm a bar!"; }
-
-
- Now, each derived class of foo gets to define its own virtOut() function
- and that is the one that is used when an object is streamed out. All <<
- operations go through the base class where they pick up virtual function
- dispatch... (very handy actually) BTW, now each derived class controls
- it's streaming, *and* it can be streamed to any ostream, cout, ofstream,
- ostrstream... See why streams are so much more powerful than printf()
- ???
-
-
- --
-
- Phil Staite, (507) 253-2529, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-